package com.rajaev.dtu.tractor.infrastructure.helper;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Created with IDEA
 * @author: tianjie
 * @Date:2019/4/9
 * @Time:9:46
 */
public class CGglibProxy implements MethodInterceptor {


    Enhancer enhancer = new Enhancer();


    public Object getProxy(Class clazz) {
        //设置需要创建的子类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("——————————————————————————");
        System.out.println("下一位请登台发言！");
        //目标方法调用
        Object result = methodProxy.invokeSuper(obj, args);
        //目标方法后执行
        System.out.println("大家掌声鼓励！");
        return result;
    }


    public static void main(String[] args) {
        CGglibProxy cGglibProxy = new CGglibProxy();
        MD5ValueGenerator md5ValueGenerator = (MD5ValueGenerator) cGglibProxy.getProxy(MD5ValueGenerator.class);
        md5ValueGenerator.test();
        md5ValueGenerator.test1();

        MD5ValueGenerator.generateValue();
    }

}
